/*
<div id="app">Hello Vue {{msg}}<h1></h1></div>

render(){ _c解析标签
  return _c('div', {id: 'app', style: {color: red; font-size: 16px}}, _v('hello', _s(msg)), _c('h'))
}
*/

const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; //{{}}
// 处理属性
function genProps(attrs) {
  let str = "";
  for (let i = 0; i < attrs.length; i++) {
    let attr = attrs[i]; // {name: 'style', value: 'color: red; font-size: 16px;'}
    if (attr.name === "style") {
      // style: {color: red; font-size: 16px}
      let obj = {};
      attr.value.split(";").forEach((item) => {
        let [key, val] = item.split(":");
        obj[key] = val;
      });
      attr.value = obj;
    }
    // 拼接
    str += `${attr.name} : ${JSON.stringify(attr.value)},`;
  }
  return `{${str.slice(0, -1)}}`;
}

// 处理子集
function genChildren(el) {
  let children = el.children;
  if (children) {
    return children.map((child) => gen(child)).join(",");
  }
}
function gen(node) {
  // console.log(node);
  // 1元素  3文本
  if (node.type === 1) {
    // 元素
    return generate(node);
  } else {
    // 文本 1只是文本  2有{{}}
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`;
    }
  }
}

export function generate(el) {
  // console.log(el);
  let children = genChildren(el);
  // console.log(children);
  let code = ` _c(${el.tag}, ${
    el.attrs.length ? `${genProps(el.attrs)}` : `null`
  },
    ${children ? `${children}` : "null"})
  `;
  console.log(code);
}
